package com.vote.business.service.impl;

import com.vote.business.domain.vo.*;
import com.vote.business.mapper.VoteDashboardMapper;
import com.vote.business.service.IVoteDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class VoteDashboardServiceImpl implements IVoteDashboardService {

    @Autowired
    private VoteDashboardMapper voteDashboardMapper;
    /**
     * 计算核心统计指标：总活动数、较昨日变化量
     */
    @Override
    public CalculateCoreVO calculateCoreStats() {
    ;    // 1. 计算总活动数（所有状态的活动）
        int totalVote = voteDashboardMapper.countTotalVote();

        // 2. 计算昨日活动总数
        LocalDate yesterday = LocalDate.now().minusDays(1);
        String yesterdayStr = yesterday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        int yesterdayTotal = voteDashboardMapper.countVoteByDate(yesterdayStr);

        // 3. 计算较昨日变化量（今日总数 - 昨日总数）
        // 注意：这里的"今日总数"是指截至当前的总数，实际业务可能需要按统计周期调整
        // 假设总活动数是累计值，直接使用
        int changeFromYesterday = totalVote - yesterdayTotal;
        String changeDesc=String.format("较昨日%s%d", changeFromYesterday >= 0 ? "+" : "", changeFromYesterday);
        return new CalculateCoreVO()
                .setChangeDesc(changeDesc)
                .setTotalVote(String.valueOf(totalVote))
                .setChangeFromYesterday(String.valueOf(changeFromYesterday));
    }
    /**
     * 获取进行中活动统计数据
     */
    @Override
    public OngoingVoteVO getOngoingVoteStats() {
        // 1. 查询进行中活动数量（状态=1）
        int ongoingCount = voteDashboardMapper.countByStatus(1);
        // 2. 查询活动总数（所有状态）

        int totalActivities = voteDashboardMapper.countTotalVote();

        // 3. 计算占比（保留整数，如57%）
        int percentage = 0;
        if (totalActivities > 0) {
            // 计算方式：(进行中数量 / 总数) * 100，四舍五入
            percentage = new BigDecimal(ongoingCount)
                    .divide(new BigDecimal(totalActivities), 2, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal(100))
                    .intValue();
        }
        return new OngoingVoteVO()
                .setOngoingCount(ongoingCount)
                .setTotalCount(totalActivities)
                .setPercentage(percentage);
    }

    @Override
    public TotalParticipationVO getTotalParticipation() {
        // 1. 计算总参与人次（去重/不去重根据业务需求，这里以不去重为例）
        long totalUsers = voteDashboardMapper.countTotalParticipants();
        // 2. 计算上周参与人次
        LocalDate today = LocalDate.now();
        // 上周起始日期（上周一）
        LocalDate lastWeekStart = today.minusWeeks(1).with(TemporalAdjusters.previousOrSame(java.time.DayOfWeek.MONDAY));
        // 上周结束日期（上周日）
        LocalDate lastWeekEnd = today.minusWeeks(1).with(TemporalAdjusters.nextOrSame(java.time.DayOfWeek.SUNDAY));
        long lastWeekUsers = voteDashboardMapper.countParticipantsByDateRange(
                lastWeekStart.atStartOfDay(),
                lastWeekEnd.atTime(23, 59, 59)
        );
        // 3. 计算本周截至今天的参与人次（用于对比上周）
        LocalDate thisWeekStart = today.with(TemporalAdjusters.previousOrSame(java.time.DayOfWeek.MONDAY));
        long thisWeekUsers = voteDashboardMapper.countParticipantsByDateRange(
                thisWeekStart.atStartOfDay(),
                today.atTime(23, 59, 59)
        );
        String weekOnWeek;
        if (lastWeekUsers == 0) {
            weekOnWeek = thisWeekUsers > 0 ? "+100%" : "0%";
        } else {
            BigDecimal growth = new BigDecimal(thisWeekUsers - lastWeekUsers)
                    .divide(new BigDecimal(lastWeekUsers), 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal(100));
            int growthInt = growth.intValue();
            weekOnWeek = (growthInt >= 0 ? "+" : "") + growthInt + "%";
        }

        return new TotalParticipationVO()
                .setTotalUsers(totalUsers)
                .setWeekOnWeek(weekOnWeek);
    }

    /**
     * 热门投票top1
     * @return
     */
    @Override
    public HotVoteTopVO selectHotVoteTop1() {
        return voteDashboardMapper.selectHotVoteTop1();
    }
    // 计算占比（保留1位小数）
    private double computePercentage(long part, long total) {
        if (total == 0) return 0;
        return new BigDecimal(part)
                .divide(new BigDecimal(total), 3, RoundingMode.HALF_UP)
                .multiply(new BigDecimal(100))
                .doubleValue();
    }
    /***
     * 活动状态分布
     * @return
     */
    @Override
    public List<VoteStatusVO> getVoteStatusDistribution() {
        // 总活动数
        int total = voteDashboardMapper.countTotalVote();
        // 各状态数量
        int ongoing = voteDashboardMapper.countByStatus(1); // 进行中
        int ended = voteDashboardMapper.countByStatus(2);   // 已结束
        int notStarted = voteDashboardMapper.countByStatus(0); // 未开始
        // 计算占比并设置颜色
        return Arrays.asList(
                new VoteStatusVO().setStatusName("进行中").setCount(ongoing)
                        .setPercentage(computePercentage(ongoing, total)).setColor("#165DFF"),
                new VoteStatusVO().setStatusName("已结束").setCount(ended)
                        .setPercentage(computePercentage(ended, total)).setColor("#86909C"),
                new VoteStatusVO().setStatusName("未开始").setCount(notStarted)
                        .setPercentage(computePercentage(notStarted, total)).setColor("#0FC6C2")
        );
    }

    /**
     * 热门投票top5
     * @return
     */
    @Override
    public List<HotVoteTopVO> selectHotVoteTop5() {
        return voteDashboardMapper.selectHotVoteTop5();
    }

    /***
     * 近30天投票创建趋势
     * @return
     */
    @Override
    public List<VoteTrendVO> getVoteCreateTrend30d() {
        LocalDate today = LocalDate.now();
        LocalDate startDate = today.minusDays(29); // 近30天
        return voteDashboardMapper.selectCreateTrendByDateRange(
                startDate.atStartOfDay(),
                today.atTime(23, 59, 59)
        );
    }



    /***
     * 重点活动选项比例
     * @return
     */
    @Override
    public List<VoteOptionRatioVO> getVoteOptionRatio(Long voteId) {
        // 该活动总票数
        long totalVotes = voteDashboardMapper.countByVoteId(voteId);
        // 各选项票数及占比
        List<VoteOptionRatioVO> options = voteDashboardMapper.selectByVoteId(voteId);

        options.forEach(option -> {
            option.setPercentage(computePercentage(option.getVotes(), totalVotes));
        });
        // 设置颜色
        options.get(0).setColor("#165DFF"); // 满意（70%）
        options.get(1).setColor("#69b1ff"); // 一般（20%）
        options.get(2).setColor("#86909C"); // 不满意（10%）
        return options;
    }
}
